import { Inject, Controller, Get, Post, Put, Body } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { UserService } from '../service/user.service';
import { User } from '../entity/user/user'


@Controller('/api/user')
export class APIController {
      @Inject()
      ctx: Context;

    @Inject()
    userService: UserService;

    @Post('/getopenid', { description: '获取openid' })
    async getopenid(@Body('code') code: string) {
        console.log(code);
        const AppId = 'wx5ad21f2f1f756979';
        const AppSecret = '5c10b57c28731a7ba84860084019acdc';
        const url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppId + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
        const Fly = require('flyio/src/node')
        const fly = new Fly();
        const result = await fly.get(url);
        const openid = JSON.parse(result.data).openid;
        const session_key = JSON.parse(result.data).session_key;
        return { success: true, message: '获取openid成功', data: { openid: openid, session_key: session_key } }
    }


    @Get('/userinfo', { description: '获取用户信息' })
    async getuserinfo(@Body('openid') openid: string){
        const result = await this.userService.getuserinfo(openid)
        return { success: true, message: '获取用户信息成功', data: {result} }
    }

    @Post('/userinfo', { description: '添加用户信息' })
    async adduser(@Body() user:User){
        const result = await this.userService.adduser(user)
        return { success: true, message: '添加用户信息成功', data: {result} }
    }

    @Put('/userinfo', { description: '修改用户信息' })
    async updateuser(@Body() user:User){
        const result = await this.userService.updateuser(user)
        return { success: true, message: '修改用户信息成功', data: {result} }
    } 
}